/*
 * Filename:    NormalDistributionServiceImpl.java
 * Copyright:   2015 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2015-2-28
 */
package com.paic.mhis.hcpms.common.community.biz.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.paic.mhis.hcpms.common.community.biz.service.NormalDistributionService;
import com.paic.mhis.hcpms.common.community.dto.ConfidenceIntervalDTO;

@Component("normalDistributionService")
public class NormalDistributionServiceImpl implements NormalDistributionService {

	// T表值

	private double[] U1_99 = { 0.01, 0.03, 0.04, 0.05, 0.06, 0.08, 0.09, 0.10, 0.11, 0.13, 0.14, 0.15, 0.16, 0.18,
			0.19, 0.20, 0.21, 0.23, 0.24, 0.25, 0.27, 0.28, 0.29, 0.30, 0.32, 0.33, 0.35, 0.36, 0.37, 0.39, 0.40, 0.41,
			0.43, 0.44, 0.45, 0.47, 0.48, 0.50, 0.51, 0.52, 0.54, 0.55, 0.57, 0.58, 0.60, 0.61, 0.63, 0.64, 0.66, 0.67,
			0.69, 0.70, 0.72, 0.74, 0.76, 0.77, 0.79, 0.81, 0.82, 0.84, 0.86, 0.88, 0.90, 0.92, 0.93, 0.95, 0.97, 0.99,
			1.01, 1.03, 1.06, 1.08, 1.10, 1.12, 1.15, 1.17, 1.20, 1.23, 1.25, 1.28, 1.31, 1.34, 1.37, 1.40, 1.44, 1.48,
			1.51, 1.55, 1.60, 1.64, 1.70, 1.75, 1.81, 1.88, 1.96, 2.05, 2.17, 2.33, 2.58 };

	@Override
	public Map<String, Object> getDistributionValues(List<Double> nums) {
		Map<String, Object> result = new HashMap<String, Object>();
		int count = nums.size();
		double totalVal = 0.0;
		double squareVal = 0.0;

		for (int i = 0; i < count; i++) {
			totalVal += nums.get(i);
		}
		double averageValue = totalVal / count;
		for (int i = 0; i < count; i++) {
			squareVal += (nums.get(i) - averageValue) * (nums.get(i) - averageValue);
		}
		double varianceValue = Math.sqrt(squareVal / count);
		result.put("averageValue", averageValue);
		result.put("varianceValue", varianceValue);
		return result;
	}

	/**
	 * 功能 获取置信区间值 公式：μ＝X的平均值±t0.025×(标准差÷√n)
	 * 
	 * @param nums
	 *            样本数据
	 * @param percent
	 *            置信度
	 * @return ConfidenceIntervalDTO 置信区间
	 */
	@Override
	public ConfidenceIntervalDTO getConfidenceInterval(List<Double> nums, double percent) {
		Map<String, Object> result = this.getDistributionValues(nums);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		BigDecimal ba = new BigDecimal(result.get("averageValue") + "");
		BigDecimal bv = new BigDecimal(result.get("varianceValue") + "");
		double averageValue = ba.doubleValue();
		double varianceValue = bv.doubleValue();
		int count = nums.size();
		ConfidenceIntervalDTO cid = new ConfidenceIntervalDTO();

		double t = U1_99[(int) (percent * 100) - 1];
		cid.setX(averageValue - t * (varianceValue / Math.sqrt(count)));
		cid.setY(averageValue + t * (varianceValue / Math.sqrt(count)));
		return cid;
	}

}
